package com.jl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.CopyBean;
import com.jl.model.DamageComponent;
import com.jl.model.DeviceComponent;
import com.jl.service.IDamageComponentService;
import com.jl.service.IDeviceComponentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author 江剑
 */
@Controller
@RequestMapping("/deviceComponent")
public class DeviceComponentController extends BaseController {

    @Autowired
    public IDeviceComponentService deviceComponentService;
    @Autowired
    public IDamageComponentService damageComponentService;


    /**
     * 一定是dataGrid
     * @param deviceId
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public ResultData componentDataGrid(Long deviceId){
        QueryWrapper<DeviceComponent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t.device_id",deviceId);
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(Constants.FIRST_PAGE);
        pageDataInfo.setSize(Constants.MAX_PAGE_SIZE);
        deviceComponentService.getDeviceComponentDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }

    /**
     * 更换零件请求
     * @param deviceComponentId 零件id
     * @return
     */
    @PostMapping("/change")
    @ResponseBody
    public ResultData changeDeviceComponent(Long deviceComponentId){
        DeviceComponent deviceComponent = deviceComponentService.getById(deviceComponentId);
        if(deviceComponent == null){
            return fail();
        }else{
//            拷贝的时候已经重置了设备的启用时间
            DamageComponent damageComponent = CopyBean.deviceComponentToDamageComponent(getUserId(),deviceComponent);

            damageComponentService.save(damageComponent);
//            重置配件平均寿命
            Integer avgLife = damageComponentService.getDeviceComponentAvgLife(deviceComponent.getDeviceId(),deviceComponent.getComponentId());
            if(avgLife!=0){
                deviceComponent.setAvgLife(avgLife);
            }
            deviceComponentService.updateById(deviceComponent);

        }
        return success(deviceComponent);
    }



}